package com.chanyachting.emall.action.index;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.chanyachting.emall.domain.Channel;
import com.chanyachting.emall.form.DockForm;
import com.chanyachting.emall.service.ChannelService;
import com.chanyachting.emall.service.DockyachtService;
import com.chanyachting.emall.serviceImpl.ChannelServiceImpl;
import com.chanyachting.emall.serviceImpl.DockyachtServiceImpl;

public class QueryDockofSubChannelAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//主页页面记录数
		int COMMON_PAGE_SIZE = 6;
		DockForm dForm = (DockForm) form;
		DockyachtService dyservice=new DockyachtServiceImpl();
		ChannelService cService = new ChannelServiceImpl();
		
		int currentPage = dForm.getCurrentPage();
		int pageSize = COMMON_PAGE_SIZE;

		int channelId = dForm.getChannelId();
		int subChannelId = dForm.getSubChannelId();
		Channel c = new Channel(channelId);
		c = cService.getOneChannel(c);
		
		if (c == null) {
			return mapping.findForward("error");
		}
		
		List<Channel> subChannelList = cService.getSubChannel(c);
		if (subChannelList == null || subChannelList.size() == 0) {
			return mapping.findForward("error");
		}
		boolean isExistSubChannel = false;
		for(Channel cn:subChannelList) {
			if (cn == null || cn.getId() == null) {
				continue;
			}
			if (cn.getId().equals(dForm.getSubChannelId())) {
				dForm.setSubChannelName(cn.getName());
				isExistSubChannel = true;
				break;
			}
		}
		if (isExistSubChannel == false) {
			return mapping.findForward("error");
		}
		dForm.setChannelName(c.getName());
		int pageCount = dyservice.QueryAllDockCountByChannelId(String.valueOf(subChannelId))/pageSize;
		
		if (pageCount%pageSize > 0) {
			pageCount = pageCount + 1;
		}
		
		if (currentPage < 1) {
			currentPage = 1;
		} else if (currentPage > pageCount) {
			currentPage = 1;
		}
		
		
		dForm.setSubChannelList(subChannelList);
		dForm.setDockList(dyservice.QueryAllDockByChannelId(currentPage, pageSize,String.valueOf(subChannelId)));
		
		return mapping.findForward("doDockOfSubChannel");
	}

}
